package 回溯;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeetCode40_组合总和 {
    private List<List<Integer>> res = new ArrayList<>();
    private int[] candidates;
    private int target;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        this.candidates = candidates;
        this.target = target;
        List<Integer> path = new ArrayList<>();
        backtrack(path,0,0);
        return res;
    }

    private void backtrack(List<Integer> path,int sum,int begin) {
        if(sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = begin;i < candidates.length;i++) {
            if(sum <= target) {
                path.add(candidates[i]);
                backtrack(path,sum+candidates[i],i+1);
                path.remove(path.size()-1);
            }
            while (i != candidates.length-1 && candidates[i] == candidates[i+1]){
                i++;
            }
        }
    }
}
